<template>
	<view class="page">
		<view class="main">
			<view class="form-wrap">
				<u-form labelWidth="220rpx">
					<u-form-item label="姓名：" prop="memberName" borderBottom>
						<u-input v-model="form.memberName" border="none" inputAlign="right" placeholder="请输入姓名" />
					</u-form-item>
					<u-form-item label="企业名称：" prop="companyName" borderBottom>
						<u-input v-model="form.companyName" border="none" inputAlign="right" placeholder="请输入企业名称" />
					</u-form-item>
					<u-form-item label="职务：" prop="position" borderBottom>
						<u-input v-model="form.position" border="none" inputAlign="right" placeholder="请输入职务" />
					</u-form-item>
					<u-form-item label="电话：" prop="mobile" borderBottom>
						<u-input v-model="form.mobile" border="none" inputAlign="right" placeholder="请输入电话" />
					</u-form-item>
					<u-form-item label="导航地址：" prop="address" borderBottom @click="chooseAds()">
						<u-input v-model="form.address" placeholder="点击选择" border="none" inputAlign="right" disabled
							disabledColor="#ffffff" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>

				</u-form>
			</view>
			<view class="form-wrap">
				<u-form labelWidth="220rpx">
					<u-form-item label="主营品牌及产品" prop="zypphcp" labelPosition="top" labelWidth="100%">
						<view style="margin-top: 20rpx;">
							<u-textarea v-model="form.zypphcp" placeholder="请输入主营品牌及产品" count maxlength="200"
								style="margin-top: 38rpx;" height="186rpx"></u-textarea>
						</view>
					</u-form-item>
				</u-form>
			</view>

			<view class="form-wrap">
				<u-form labelWidth="220rpx">
					<u-form-item label="销售渠道：" prop="xsqudao" borderBottom @click="salseQudaoShow = true">
						<u-input v-model="form.xsqudao" placeholder="点击选择" border="none" inputAlign="right" disabled
							disabledColor="#ffffff" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="合作满意度：" prop="hzmyd" borderBottom @click="hezuomydShow = true">
						<u-input v-model="form.hzmyd" placeholder="点击选择" border="none" inputAlign="right" disabled
							disabledColor="#ffffff" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="客户属性：" prop="khsx" borderBottom @click="choosekhsx">
						<u-input v-model="form.khsx" placeholder="点击选择" border="none" inputAlign="right" disabled
							@click="showSex = true; hideKeyboard()" disabledColor="#ffffff" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="客户照片：" prop="headImg" borderBottom>
						<view class="tx-wrap">
							<u-avatar size="80rpx" :src="form.headImg?fileServer+form.headImg:null"
								@click="onChooseAvatar"></u-avatar>
						</view>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="身份：" prop="shenfenLabel" borderBottom @click="chooseShenFen()">
						<u-input v-model="form.shenfenLabel" placeholder="点击选择" border="none" inputAlign="right"
							disabled disabledColor="#ffffff" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="行业分类：" prop="hyflInfo" borderBottom @click="toHyfl()" v-if="form.type!==''">
						<u-input v-model="form.hyflInfo" placeholder="点击选择" border="none" inputAlign="right" disabled
							disabledColor="#ffffff" />
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="备注：" prop="beizhu" labelPosition="top" labelWidth="100%">
						<view style="margin-top: 20rpx;">
							<u-textarea v-model="form.beizhu" placeholder="请输入备注信息" count maxlength="200"
								 height="186rpx"></u-textarea>
						</view>
						
					</u-form-item>
				</u-form>
			</view>
		</view>
		<view class="btm-wrap-tc">

		</view>
		<view class="btm-wrap">
			<view class="btn confim-btn" @click="submit">
				{{id?'编辑':'添加'}}
			</view>
		</view>
		<u-popup :show="salseQudaoShow" @close="salseQudaoShow = false">
			<view style="padding: 32rpx;">
				<u-checkbox-group v-model="form.xsqudao" placement="column">
					<u-checkbox :customStyle="{marginBottom: '8px'}" v-for="(item, index) in salseQudao" :key="index"
						:label="item.dictLabel" :name="item.dictLabel">
					</u-checkbox>
				</u-checkbox-group>
				<u-button type="primary" shape="circle" text="确定" @click="salseQudaoShow = false"></u-button>
			</view>
		</u-popup>
		<u-popup :show="hezuomydShow" @close="hezuomydShow = false">
			<view style="padding: 32rpx;">
				<u-checkbox-group v-model="form.hzmyd" placement="column">
					<u-checkbox :customStyle="{marginBottom: '8px'}" v-for="(item, index) in hezuomyd" :key="index"
						:label="item.dictLabel" :name="item.dictLabel">
					</u-checkbox>
				</u-checkbox-group>
				<u-button type="primary" shape="circle" text="确定" @click="hezuomydShow = false"></u-button>
			</view>
		</u-popup>
		<hyflSelect ref="hyflSelect" @selectHyfl="selectHyfl"></hyflSelect>
		<u-modal :show="userInfoShow" title="初次登录,请完善用户信息">
			<view>
				<view style="text-align: center;">
					<button class="avatar-wrapper" open-type="chooseAvatar"
						style="padding: 0;display: inline-block;">
						<u-avatar shape="square" :src="userInfo.headImg?fileServer+userInfo.headImg:null"></u-avatar>
					</button>
				</view>
				<view style="margin-top: 20rpx;">
					<u-input placeholder="请输入昵称" border="surround" v-model="userInfo.ncName" type="nickname"></u-input>
				</view>
			</view>
			<u-button text="一键获取手机号并绑定用户信息" open-type="getPhoneNumber" @getphonenumber="getphonenumber"
				slot="confirmButton" type="primary" plain></u-button>
		</u-modal>
	</view>
</template>

<script>
	import hyflSelect from "../../../components/hyflSelect/hyflSelect.vue"
	export default {
		components: {
			hyflSelect
		},
		data() {
			return {
				userInfoShow:false,
				form: {
					"address": "",
					"area": "",
					"beizhu": "",
					"city": "",
					"companyName": "",
					"fzqy": "",
					"headImg": "",
					"hzmyd": '',
					"khsx": '',
					"lat": "",
					"lng": "",
					"memberName": "",
					"mobile": "",
					"position": "",
					"province": "",
					"xsqudao": '',
					"type": '',
					"shenfenLabel": '',
					"zypphcp": '',
					"hyfl": [],
					"hyflInfo": [],
				},
				salseQudao: [],
				hezuomyd: [],
				customshuxing: [],
				salseQudaoShow: false,
				hezuomydShow: false,
				customshuxingShow: false,
				fileServer: this.$fileServer,
				id: null,
				userMemberId:null,
				yqrId:'',//邀请人Id
			};
		},
		onLoad(o) {
			if(o.yqrId){
				this.yqrId = o.yqrId;
				if(!uni.getStorageSync('memberId')){
					this.toLogin();
				}else{
					this.getUserInfo();
				}
				// 邀请客户
				
			}
			this.getDict()
			if (o.id) {
				this.id = o.id
				uni.setNavigationBarTitle({
					title: "编辑客户备忘录"
				})
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.on('acceptDataFromOpenerPage', (data) => {
					this.form = {
						...data.data
					}
					this.form.xsqudao = this.form.xsqudao.split(',')
					this.form.hzmyd = this.form.hzmyd.split(',')
					this.form.hyfl = this.form.hyfl.split(',')
					this.form.hyflInfo = this.form.hyflInfo.split(',')
					for (let i = 0; i < getApp().globalData.typeList.length; i++) {
						if (getApp().globalData.typeList[i].value === this.form.type) {
							this.form.shenfenLabel = getApp().globalData.typeList[i].label
						}
					}
				})
			}
			if(o.memberId){
				this.userMemberId = o.memberId
			}
		},
		methods: {
			getUserInfo(){
				this.$api.member.getPersonCenterById().then(res => {
					console.log('res', res);
					let member = res.data.member;
					this.form.memberName = member.name
					this.form.mobile = member.mobile
					this.form.type = member.type||''
					if(member.qyName){
						this.form.companyName = member.qyName
					}
					if(member.headImg){
						this.form.headImg = member.headImg
					}
					if(member.zypphcp){
						this.form.zypphcp = member.zypphcp
					}
					if(member.position){
						this.form.position = member.position
					}
					if(member.hyfl){
						this.form.hyfl = member.hyfl.split(',')
					}
					if(member.hyflInfo){
						this.form.hyflInfo = member.hyflInfo.split(',')
					}
					// 0-经销商；1-厂家；2-产业链
					if(member.type==0){
						this.form.shenfenLabel= '经销商'
					}else if(member.type==1){
						this.form.shenfenLabel= '厂家'
					}else if(member.type==2){
						this.form.shenfenLabel= '产业链'
					}
				})
			},
			toLogin() {
				uni.login({
					provider: "weixin",
					success: (loginRes) => {
						if (loginRes.errMsg === "login:ok") {
							// code: loginRes.code
							this.$api.member.wxAuthLogin({
								code: loginRes.code,
								yqrId:this.yqrId,
							}).then(res => {
								this.userInfo = res.data
								uni.setStorageSync('memberId', res.data.id)
								if(res.data.companyId){
									uni.setStorageSync('companyId', res.data.companyId||'');
								}
								this.userInfoShow = true
								if (uni.$u.test.isEmpty(res.data.name) || uni.$u.test.isEmpty(res.data
										.mobile)) {
									this.userInfoShow = true
								} 
							})
						}
					},
					complete(e) {
						console.log('rese', e);
					}
				})
			},
			getphonenumber(code) {
				this.$api.member.wxAuthMobile({
					"headImg": this.userInfo.headImg,
					"ncName": this.userInfo.ncName,
					code: code.detail.code
				}).then(res => {
					this.userInfo = res.data
					let member = res.data
					this.form.memberName = member.name
					this.form.mobile = member.mobile
					this.form.type = member.type||''
					if(member.qyName){
						this.form.companyName = member.qyName
					}
					if(member.headImg){
						this.form.headImg = member.headImg
					}
					if(member.zypphcp){
						this.form.zypphcp = member.zypphcp
					}
					if(member.hyfl){
						this.form.hyfl = member.hyfl.split(',')
					}
					if(member.hyflInfo){
						this.form.hyflInfo = member.hyflInfo.split(',')
					}
					// 0-经销商；1-厂家；2-产业链
					if(member.type==0){
						this.form.shenfenLabel= '经销商'
					}else if(member.type==1){
						this.form.shenfenLabel= '厂家'
					}else if(member.type==2){
						this.form.shenfenLabel= '产业链'
					}
					this.userInfoShow = false
					
				})
			},
			
			submit() {
				let form = JSON.parse(JSON.stringify(this.form))
				if(form.xsqudao){
					form.xsqudao = form.xsqudao.join(',')
				}
				if(form.hzmyd){
					form.hzmyd = form.hzmyd.join(',')
				}
				if(form.hyfl){
					form.hyfl = form.hyfl.join(',')
				}
				if(form.hyflInfo){
					form.hyflInfo = form.hyflInfo.join(',')
				}
				if (uni.$u.test.isEmpty(this.id)) {
					if(this.yqrId){//邀请人他人帮填
						form.memberId = this.yqrId;
						form.notToken = true;
						form.glMemberId = this.userMemberId||uni.getStorageSync("memberId")
					}else if(this.userMemberId){
						form.memberId = this.userMemberId||uni.getStorageSync("memberId")
					}
					console.log(form)
					this.$api.custom.addCustombwl(form).then(res => {
						uni.showToast({
							title: "添加成功",
						})
						setTimeout(() => {
							if(this.yqrId){
								uni.switchTab({
									url:'/pages/tabBar/index/index'
								})
							}else{
								uni.navigateBack()
							}
						}, 1500)
					})
				} else {
					this.$api.custom.addCustombwl(form).then(res => {
						uni.showToast({
							title: "编辑成功",
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					})
				}
			},
			choosekhsx() {
				uni.showActionSheet({
					itemList: this.customshuxing.map(i => {
						return i.dictLabel
					}),
					success: (res) => {
						this.form.khsx = this.customshuxing[res.tapIndex].dictLabel
						this.$forceUpdate()
					}
				})
			},
			chooseShenFen() {
				uni.showActionSheet({
					itemList: getApp().globalData.typeList.map(i => {
						return i.label
					}),
					success: (res) => {
						this.form.type = getApp().globalData.typeList[res.tapIndex].value
						this.form.shenfenLabel = getApp().globalData.typeList[res.tapIndex].label
						this.$forceUpdate()
					}
				})
			},
			selectHyfl(obj) {
				console.log('obj', obj);
				this.form.hyfl = obj.list
				this.form.hyflInfo = obj.listName
			},
			toHyfl() {
				this.$refs.hyflSelect.openModal()
			},
			onChooseAvatar(res) {
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.uploadFile({
							url: this.$serverUrl + '/api/member/uploadFile.client', //仅为示例，非真实的接口地址
							filePath: tempFilePaths[0],
							name: 'upload',
							success: (uploadFileRes) => {
								this.form.headImg = JSON.parse(uploadFileRes.data).data
							}
						});
					}
				});
			},
			getDict() {
				this.$api.member.getDictList('salseQudaoCode').then(res => {
					this.salseQudao = res.data
				})
				this.$api.member.getDictList('hezuomydCode').then(res => {
					this.hezuomyd = res.data
				})
				this.$api.member.getDictList('customshuxingCode').then(res => {
					this.customshuxing = res.data
				})
			},
			extractProvinceCityDistrict(address) {
				// 定义省市区的正则表达式
				const regex = /(.*?[省市自治区壮回维吾尔苗藏土蒙古哈达])?(.*?[市区县旗])?(.*?区)?/;

				// 使用正则表达式匹配地址
				const matches = address.match(regex);

				// 提取匹配的省、市、区信息
				const province = matches[1] || '';
				const city = matches[2] || '';
				const district = matches[3] || '';

				return {
					province,
					city,
					district
				};
			},
			chooseAds() {
				uni.chooseLocation({
					success: (res) => {
						let qy = this.extractProvinceCityDistrict(res.address)
						this.form.province = qy.province
						this.form.city = qy.city
						this.form.area = qy.district
						this.form.address = res.address
						this.form.lat = res.latitude
						this.form.lng = res.longitude
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background-color: #F5F5F5;

		.main {
			position: relative;
			padding: 1px 30rpx;

			.page-title {
				height: 80rpx;
				line-height: 80rpx;
				font-size: 28rpx;
			}

			.form-wrap {

				background: #FFFFFF;
				border-radius: 20rpx;
				padding: 0 30rpx;
				margin-top: 24rpx;

				.tx-wrap {
					display: flex;
					width: 100%;
					justify-content: flex-end;
				}

				.tx {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;

				}
			}
		}
	}

	.btm-wrap-tc {
		width: 100%;
		height: 170rpx;

	}

	.btm-wrap {
		width: 100%;
		position: fixed;
		bottom: 50rpx;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: space-around;
		z-index: 99;

		.btn {
			width: 244rpx;
			height: 70rpx;
			border-radius: 42rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 26rpx;

			&.return-btn {
				border: 1px solid #EC2424;
				color: #EC2424;
				background-color: #FFFFFF;
			}

			&.confim-btn {
				color: #FFFFFF;
				background: #EC2424;
			}
		}
	}
</style>